package com.dxp.utils;

import com.alibaba.fastjson.JSON;
import com.apache.tools.StrUtil;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.Map;

/** description: http请求
 * @author Hou Dayu 创建时间：2019/8/11
 */
public class HttpService {

	private static Logger logger = Logger.getLogger(HttpService.class);

	public static String sendGetHttp(String url, Map bodyParams) {
		return sendHttp(url,"get",null,bodyParams);
	}

	public static String sendPostHttp(String url, Map bodyParams) {
		return sendHttp(url,"post",null,bodyParams);
	}

	public static String sendGetHttp(String url, Map bodyParams,Map<String,String> headParams) {
		return sendHttp(url,"get",headParams,bodyParams);
	}

	public static String sendPostHttp(String url, Map bodyParams,Map<String,String> headParams) {
		return sendHttp(url,"post",headParams,bodyParams);
	}
	public static String sendHttp(String url,String method,Map<String,String> headParams, String bodyParams,String format) {
		CloseableHttpResponse response = null;
		CloseableHttpClient client = null;
		try {
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(500).setSocketTimeout(30000).build();
			if("get".equalsIgnoreCase(method)){
				// 构造请求
				HttpEntityEnclosingRequestBase httpEntity = new HttpEntityEnclosingRequestBase() {
					@Override
					public String getMethod() {
						return "GET";
					}
				};
				if(!StrUtil.isEmpty(headParams) && !headParams.isEmpty()){
					for (Map.Entry<String,String> entry : headParams.entrySet()) {
						httpEntity.setHeader(entry.getKey(), entry.getValue());
					}
				}
				client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
				httpEntity.setURI(URI.create(url));
				if(StrUtil.isNotNull(bodyParams)) {
					if("xml".equalsIgnoreCase(format)){
						httpEntity.setEntity(new StringEntity(bodyParams, ContentType.APPLICATION_XML));
					}else {
						httpEntity.setEntity(new StringEntity(bodyParams, ContentType.APPLICATION_JSON));
					}
				}
				response = client.execute(httpEntity);
			} else {
				// 构造请求
				HttpPost httpEntity = new HttpPost(url);
				client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
				if(!StrUtil.isEmpty(headParams) && !headParams.isEmpty()){
					for (Map.Entry<String,String> entry : headParams.entrySet()) {
						httpEntity.setHeader(entry.getKey(), entry.getValue());
					}
				}
				if(StrUtil.isNotNull(bodyParams)) {
					if("xml".equalsIgnoreCase(format)){
						httpEntity.setEntity(new StringEntity(bodyParams, ContentType.APPLICATION_XML));
					}else {
						httpEntity.setEntity(new StringEntity(bodyParams, ContentType.APPLICATION_JSON));
					}
				}
				response = client.execute(httpEntity);
			}

			if (response != null && response.getStatusLine().getStatusCode() == 200) {
				String line = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
				return line;
			}
		} catch (Exception e) {
			logger.error("连接失败：",e);
		} finally {
			close(response,client,null);
		}
		return null;
	}
	public static String sendHttp(String url,String method,Map<String,String> headParams, Map bodyParams) {
		return sendHttp(url,method,headParams,JSON.toJSONString(bodyParams),"json");
	}

	public static String sendHttp(String url, MultipartFile file,String inputFilename, Map<String,String> headParams, Map<String,String> urlParams) {
		CloseableHttpResponse response = null;
		CloseableHttpClient client = null;
		try {
			RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60000).setConnectTimeout(1000).setSocketTimeout(600000).build();
			StringBuilder sb = new StringBuilder(url);
			if(!StrUtil.isEmpty(urlParams) && !urlParams.isEmpty()){
				if(url.indexOf("?")==-1){
					sb.append("?");
				} else {
					sb.append("&");
				}
				for (Map.Entry<String,String> entry : urlParams.entrySet()) {
					sb.append(entry.getKey()+"="+ entry.getValue()+"&");
				}
			}
			// 构造请求
			HttpPost httpPost = new HttpPost(sb.toString());
			client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
			MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
			builder.setCharset(Charset.forName("UTF-8")).addBinaryBody(inputFilename, file.getInputStream(), ContentType.APPLICATION_OCTET_STREAM, file.getOriginalFilename());
			HttpEntity entity = builder.build();
			httpPost.setEntity(entity);
			if(!StrUtil.isEmpty(headParams) && !headParams.isEmpty()){
				for (Map.Entry<String,String> entry : headParams.entrySet()) {
					httpPost.setHeader(entry.getKey(), entry.getValue());
				}
			}
			response = client.execute(httpPost);
			if (response != null && response.getStatusLine().getStatusCode() == 200) {
				String line = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
				return line;
			}
		} catch (Exception e) {
			logger.error("连接失败：",e);
		} finally {
			close(response,client,null);
		}
		return null;
	}

	private static void close(CloseableHttpResponse response, CloseableHttpClient client, BufferedReader bufferedReader){
		try {
			if(null != bufferedReader){
				bufferedReader.close();
			}
			if (response != null) {
				response.close();
			}
			if(null != client) {
				client.close();
			}
		} catch (IOException e) {
			logger.error("流关闭失败：",e);
		}
	}
}
